package com.negative.activities;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

import com.negative.data.EventItem;
import com.negative.logic.HomeScreenShortcutAdapter;
import com.negative.logic.MenuListener;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewFlipper;

public class MainMenu extends Activity {

	private GridView gridView;
	private ViewFlipper flipper;
	private ImageView menuButton;
	private MenuListener menuListener;
	private TextView specialEventsHeader;
	private SimpleDateFormat dateWithTime;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_menu_layout);

		initialize();
		
		addViewsToFlipper(this, (NegativeApplication) this.getApplication());

		gridView.setAdapter(new HomeScreenShortcutAdapter(this));
		gridView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_MOVE) {
					return true;
				}
				return false;
			}
		});
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				Intent intent;

				switch (position) {
				case 0:
					intent = new Intent(MainMenu.this, EventListActivity.class);
					startActivity(intent);
					break;

				case 1:
					intent = new Intent(MainMenu.this,
							SearchEventActivity.class);
					startActivity(intent);
					break;
				default:
					break;
				}
			}

		});

		Thread flipperThread = new Thread() {
			public void run() {
				while (true) {
					try {
						sleep(2000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						// e.printStackTrace();
					}
					runOnUiThread(new Runnable() {
						public void run() {
							flipper.showNext();
						}
					});
				}
			}
		};
		flipperThread.start();
	}

	public void addViewsToFlipper(final Context context,
			final NegativeApplication app) {

		ArrayList<View> todayEvents = new ArrayList<View>();
		for (EventItem event : app.getEventList()) {
			if (event.isSpecial()) {
				if (event.getPicture() != null && !event.getPicture().isEmpty()) {
					Bitmap icon = ((NegativeApplication) getApplication())
							.getEventPic(event.getPicture());

					View v = getLayoutInflater().inflate(R.layout.special_event_layout, null);
					TextView title = (TextView)v.findViewById(R.id.special_event_title);
					title.setText(event.getName());
					ImageView view = (ImageView)v.findViewById(R.id.special_event_pic);
					view.setImageBitmap(icon);
					view.setTag(event);
					view.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {

							showDatesDialog(v, app, context);
						}
					});
					flipper.addView(v);
				}
			} else {
				Date eventStartDate = event.getStartDate();
				if (isDateInCurrentWeek(eventStartDate)) {
					if (event.getPicture() != null
							&& !event.getPicture().isEmpty()) {
						Bitmap icon = ((NegativeApplication) getApplication())
								.getEventPic(event.getPicture());
 
						View v = getLayoutInflater().inflate(R.layout.special_event_layout, null);
						TextView title = (TextView)v.findViewById(R.id.special_event_title);
						title.setText(event.getName());
						ImageView view = (ImageView)v.findViewById(R.id.special_event_pic);
						view.setImageBitmap(icon);
						view.setTag(event);
						view.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {

								showDatesDialog(v, app, context);

							}
						});
						todayEvents.add(v);
					}
				}
			}
		}
		if (flipper.getChildCount() == 0) {
			specialEventsHeader.setText(getString(R.string.week_header));
			for (View v : todayEvents) {
				flipper.addView(v);
			}
		}

	}

	private void initialize() {

		menuListener = new MenuListener(this);
		gridView = (GridView) findViewById(R.id.gridView1);
		flipper = (ViewFlipper) findViewById(R.id.viewFlipper);
		menuButton = (ImageView) findViewById(R.id.menu_icon);
		specialEventsHeader = (TextView) findViewById(R.id.event_page_date_label);

		menuButton.setOnClickListener(menuListener);
		
		dateWithTime = new SimpleDateFormat("EEE dd/MM/yyyy HH:mm", new Locale("iw-il"));
	}

	public boolean isDateInCurrentWeek(Date date) {
		Calendar currentCalendar = Calendar.getInstance();
		int week = currentCalendar.get(Calendar.WEEK_OF_YEAR);
		int year = currentCalendar.get(Calendar.YEAR);
		Calendar targetCalendar = Calendar.getInstance();
		targetCalendar.setTime(date);
		int targetWeek = targetCalendar.get(Calendar.WEEK_OF_YEAR);
		int targetYear = targetCalendar.get(Calendar.YEAR);
		return week == targetWeek && year == targetYear;
	}

	private void showDatesDialog(View v, NegativeApplication app, final Context context) {
		
		String name = ((EventItem)v.getTag()).getName();
		final HashMap<String, EventItem> eventMap = new HashMap<String, EventItem>();
		for (EventItem event : app.getEventList()) {
			if (event.getName().equals(name))
				eventMap.put(dateWithTime.format(event.getStartDate()), event);
		}

		String[] dates = eventMap.keySet().toArray(new String[eventMap.values().size()]);
		Date[] dateArr = new Date[dates.length];
		for (int i = 0; i < dates.length; i++) {
			try {
				dateArr[i] = dateWithTime.parse(dates[i]);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
//				e.printStackTrace();
			}
		}
//		Arrays.sort(dates);
		Arrays.sort(dateArr);
		for (int i = 0; i < dates.length; i++) {
			dates[i] = dateWithTime.format(dateArr[i]);
		}
		ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(context,
				android.R.layout.simple_list_item_1, dates);
		
		final Dialog dateDialog = new Dialog(context);
		dateDialog.setContentView(R.layout.event_date_list_layout);
		dateDialog.setTitle(R.string.chooseDate);
		ListView eventDates = (ListView) dateDialog
				.findViewById(R.id.event_date_list);
		eventDates.setAdapter(listAdapter);
		eventDates.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				String date = (String)arg0.getItemAtPosition(arg2);
				EventItem event = eventMap.get(date);
				Intent intent = new Intent(context, EventActivity.class);
				intent.putExtra("EventItem", event);
				startActivity(intent);
				dateDialog.dismiss();
			}
		});
		dateDialog.show();
	}
}
